import _ from "lodash"
import BigJs from 'big.js'
import { deleteAction, getAction, downFile, getFileAccessHttpUrl, putAction, httpAction, postAction } from '@/api/manage'
import store from '@/store'
import moment from 'moment'
console.log(store.getters.departInfo.orgLevel);
export const CommonMixin = {
  data() {
    return {
      ipagination: {
        size: 'small',
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '50', '100', '200', '300'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: false,
        showSizeChanger: true,
      },
      OrgLevel: store.getters.departInfo.orgLevel,
      url: {
        upDataFlag: '/sjxxzhbb/jnxm/updSubmitFlag',
      },
      yearPickShow: "",
      TotalData: [],
      cacheData: [],
      reportSelectIds: [],
      disableMixinCreated: true,
      disableMonmomMixinCreated: true,
      targetColListIndex: 0,
      isNeedSerial: true,
      SerialNumberData: [
        // 境内境外
        {
          id: 'undefined1',
          serialnumber: true,
          ejdw: '2',
          sjdw: '3',
          gcmc: '4',
          xmlx: '5',
          tzcblx: '6',
          xmszd: '7',
          xmzt: '8',
          xzlb: '9',
          xzmc: '10',
          sflrzlqd: '11',
          htkgText: '12',
          htwgText: '13',
          sjkgText: '14',
          sjjgysText: '15',
          tgrqText: '16',
          ygjjText: '17',
          sfjgjs: '18',
          csht: '19',
          bcht: '20',
          mblr: '21',
          mblrl: '22',
          klzmlr: '23',
          klygjj: '24',
          dpfygjj: '25',
          htlycb: '26',
          yfswlcb: '27',
          xlclcb: '28',
          sjglf: '29',
          kllr: '30=24+25-26-27+28',
          kcwzZm: '31',
          kcwzSj: '32',
          ysgck: '33',
          yszbj: '34',
          gsdzsjzj: '35',
          zmyfwbzw: '36',
          reason: '37',
          yjmckh: '38',
          jsyjyjxkh: '39',
          remark: '40',
        },
        //投资公司
        {
          id: 'undefined2',
          serialnumber: true,
          ejdw: "1",
          zbbzhb: "1",
          xmmc: "2",
          xmszd: "3",
          xmlx: "4",
          yzmc: "5",
          xmzt: "6",
          sfgfgs: "7",
          kgrq: "8",
          wgrq: "9",
          sjkgrq: "10",
          jgysrq: "11",
          tgrq: "12",
          ygjjrq: "13",
          tzgm: "14",
          ztze: "15",
          jatz: "16",
          fjatz: "17",
          tzgs: "18",
          yjj: "19",
          dpfbgsp: "20",
          hte: "21",
          yjjbgtz: "22",
          ywwjbgtz: "23",
          cjdwjc: "24",
          sjgck: "25",
          cjgck: "26",
          yszkGck: "27",
          cqyszGck: "28",
          sssj: "29",
          sdje: "30",
          reason: "31",
          remark: "32",
        },
        // 股份公司
        {
          id: 'undefined3',
          serialnumber: true,
          zbbzhb: "1",
          xmmc: "2",
          gcszd: "3",
          xmlx: "4",
          yzlb: "5",
          yzmc: "6",
          xmzt: "7",
          ifzxzl: "8",
          htydrq: "9",
          wgrq: "10",
          sjkgrq: "11",
          jgysrq: "12",
          tgrq: "13",
          ygjjrq: "14",
          yjj: "15",
          dpfbgsp: "16",
          hte: "17",
          yjjbgtc: "18",
          ywwjbgtc: "19",
          cjdwjc: "20",
          sjgck: "21",
          cjdwgck: "22",
          yszkGck: "23",
          cqyskGck: "24",
          reason: "25",
          remark: "26",
        },
        // 设计院
        {
          id: 'undefined4',
          serialnumber: true,
          name: "2",
          xmmc: "3",
          xmlx: "4",
          tzcblx: "5",
          xmszd: "6",
          xzlb: "7",
          xzmc: "8",
          xmzt: "9",
          htkgText: "10",
          htwgText: "11",
          sjkgText: "12",
          sjjgysText: "13",
          tgrqText: "14",
          ygjjText: "15",
          sfjgjs: "16",
          csht: "17",
          bcht: "18",
          klzmlr: "19",
          klygjj: "20",
          dpfygjj: "21",
          htlycb: "22",
          yfswlcb: "23",
          xlclcb: "24",
          sjglf: "25",
          kllr: "26=20+21-22-23+24",
          yjj: "27",
          dpfbgsp: "28",
          fbdwhte: "29",
          yjjBgtc: "30",
          ywjjBgtc: "31",
          gfbdwjc: "32",
          ysgck: "33",
          yszbj: "34",
          sjsdgck: "35",
          zffbdw: "36",
          yfgck: "37",
          reason: "38",
          remark: "39",
        }
      ],
      total: 0,
      dataEjdw: [],
      dataGcmc: [],
      model: {},
      fetching: false,
      upLoading: false
    }
  },
  mounted() {
    if (this.disableMonmomMixinCreated)
      this.EnhanceLoad()
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
          this.reportSelectIds = [...selectedRowKeys]
        },
        selectedRowKeys: this.reportSelectIds,
        getCheckboxProps: record => {
          if (record.submitFlag == '已提交') {
            this.reportSelectIds.push(record.id)
          }
          return {
            props: {
              disabled: record.totalName === '合计' || record.serialnumber,
              name: record.name,
              defaultChecked: record.submitFlag == '已提交', // 该属性用于默认勾选处理
            },
          }
        },
      }
    },
  },
  methods: {
    openOrganModelParam(refName, title) {
      this.$refs[refName].title = title
      this.$refs[refName].show()
    },
    getDataParam(data, modelName) {
      this.model[modelName] = data[0].label
    },
    openOrganModel() {
      this.$refs.departModal.title = '项目名称'
      this.$refs.departModal.show()
    },
    // 表头查询
    searchQuery() {
      Object.keys(this.model).map((i) => {
        this.queryParam[i] =
          this.model[i] == null ? null : typeof this.model[i] == 'object' ? this.model[i].join(',') : this.model[i]
        if (i == 'sjjgysText' || i == 'tgrqText' || i == 'jgysrqText') {
          this.queryParam[i] = this.queryParam[i] ? this.queryParam[i] + '01日' : undefined
        }
      })
      this.loadData()
    },
    searchReset() {
      this.queryParam = {}
      this.model = this.$options.data().model
      this.EnhanceLoad()
    },
    OnExportList() {
      Object.keys(this.model).map((i) => {
        this.queryParam[i] =
          this.model[i] == null ? null : typeof this.model[i] == 'object' ? this.model[i].join(',') : this.model[i]
        if (i == 'sjjgysText' || i == 'tgrqText' || i == 'jgysrqText') {
          this.queryParam[i] = this.queryParam[i] ? this.queryParam[i] + '01日' : undefined
        }
      })
      getAction(this.url.exportList, { ...this.queryParam }).then((res) => {
        if (res.success && res.result) {
          this.$message.success('正在下载，请稍等！')
          const url = `${window._CONFIG['domianURL']}/sys/common/static${res.result}`
          window.open(url, '_blank')
        } else { }
      })
    },
    //  搜索时执行
    handeleSearch: _.debounce(function (value = '', dataIndex) {
      // setSelectedKeys(value ? [value] : [])
      if (dataIndex == 'ejdw') {
        this.getDataDeptName(value)
      } else {
        this.getDataGcmcName(value)
      }
    }, 300),
    getDataGcmcName(keyword = '') {
      this.fetching = true
      getAction(this.searchUrl.gcmc, { keyword }).then((result) => {
        if (result.success) {
          this.dataGcmc = result.result
        } else {
          this.$message.warning(result.message)
        }
        this.fetching = false
      })
    },
    getDataDeptName(keyword = '') {
      this.fetching = true
      getAction(this.searchUrl.ejdw, { keyword }).then((result) => {
        if (result.success) {
          this.dataEjdw = result.result
        } else {
          this.$message.warning(result.message)
        }
        this.fetching = false
      })
    },

    onShowSizeChange(current, pageSize) {
      this.ipagination.pageSize = pageSize
      this.ipagination.current = 1
      this.loadData()
    },
    handleTableChange(current, pageSize) {
      console.log(current, pageSize)
      this.ipagination.current = current
      this.ipagination.pageSize = pageSize
      this.loadData()
    },
    //  加载第一页和合计行
    async EnhanceLoad(flag = true) {
      this.TotalData = []
      if (flag) {
        await this.getTotalData()
      }
      await this.loadData(1)
    },
    //  加载当前也和合计行
    async CurrentPageEnhanceLoad(flag = true) {
      this.TotalData = []
      if (flag) {
        await this.getTotalData()
      }
      await this.loadData()
    },
    //  查询
    searchQuery() {
      this.EnhanceLoad()
    },
    //  表格中自定义渲染的文字
    transformVnode(text) {
      return <span style="font-weight:700">{text}</span>
    },
    //  表格中自定义渲染 a-input
    TransformVnodeInput(vm, text, record, length = 8) {
      if (record.editable) {
        return (
          <a-input
            value={text}
            onChange={(e) => this.handleChangeInput(e.target.value, record.id)}
          />
        )
      } else if (text) {
        if (text.length > length)
          return (
            <j-ellipsis value={text} length={length} />
          )
        else
          return (<span>{text}</span>)
      } else {
        return undefined
      }
    },
    //  表格中自定义渲染 ----按文字长度不同选取合适的标签
    TransformVnodeEllipsis(text, record, col, length = 8) {
      if (record.editable) {
        return (
          <a-input
            value={text}
            onChange={(e) => this.handleChangeInput(e.target.value, record.id, col)}
          />
        )
      } else if (text) {
        if (text.length > length)
          return (
            <j-ellipsis value={text} length={length} />
          )
        else
          return (<span>{text}</span>)
      } else {
        return undefined
      }
    },
    //  上传之前的钩子函数
    beforeUpload(file, fileList) {
      return new Promise((resolve, reject) => {
        this.getIsExistenceExcel().then((result) => {
          if (result.code == 200) {
            resolve(true)
          } else {
            let msg = '当前单位已导入，是否覆盖?'
            if (result.code == 501)
              msg = '导入表格中如果存在相同的项目名称会覆盖导入！'
            this.confirm(msg).then((res) => {
              if (res) {
                resolve(true)
              } else {
                this.$message.warning('上传取消')
                reject(false)
              }
            })
          }
        })
      })
    },
    //  请求当前上传文件是否存在
    getIsExistenceExcel() {
      return getAction(this.url.isExistenceExcel)
    },
    //  确认弹窗
    async confirm(msg) {
      return new Promise((resolve, reject) => {
        this.$confirm({
          title: msg,
          okText: '确认',
          cancelText: '取消',
          onOk() {
            resolve(true)
          },
          onCancel() {
            resolve(false)
          },
        })
      })
    },
    //  flag 表示需不需要请求合计
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() // 查询条件
      this.loading = true
      // this.dataSource=[]
      return getAction(this.url.list, params).then((res) => {
        if (res.success) {
          // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          if (this.TotalData.length > 0) {
            this.dataSource = [].concat(this.TotalData[0], res.result.records || res.result)
          }
          else
            this.dataSource = res.result.records || res.result || []
          this.cacheData = _.cloneDeep(this.dataSource)
          // 加序号
          if (this.isNeedSerial)
            this.dataSource.unshift(this.SerialNumberData[this.targetColListIndex])

          if (res.result.total) {
            this.total = res.result.total
          } else {
            this.total = 0
          }
          // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        } else {
          this.$message.warning(res.message)
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    //取整函数向上取整  ----> 因为要算 分页页数*每页多加的数据=当前数据量
    RoundNumbers(total, pageSize, additionPageNum) {
      if (total % pageSize == 0) {
        return (total / pageSize) * additionPageNum
      } else {
        return Number.parseInt((total / pageSize + 1)) * additionPageNum
      }
    },
    //  上传接口
    handleImportExcel(info) {
      this.upLoading = true
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
        this.upLoading = false
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          if (this.disableMonmomMixinCreated)
            this.EnhanceLoad()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
        this.upLoading = false
      } else if (info.file.status === 'error') {
        if (info.file.response.status === 500) {
          const data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes('Token失效')) {
            Modal.error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload()
                })
              }
            })
          }
        } else {
          this.$message.error(`文件上传失败: ${info.file.msg} `)
        }
        this.upLoading = false
      }
    },
    // 请求合计
    getTotalData() {
      var params = this.getQueryParams() // 查询条件
      return getAction(this.url.hjlist, params).then((res) => {
        if (res.success) {
          if (res.result) {
            let data = res.result[0] || res.result
            this.TotalData = [{ ...data, totalName: '合计', id: 'undefinedx' }]
          }
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //  请求项目名称
    getProjectNames(keyword = '') {
      getAction(this.url.xmmc, { xmmc: keyword }).then(res => {
        if (res.success) {
          this.xmmcData = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 操作 ---> 按钮的点击事件
    handleMenuClick(e, record) {
      if (e.key == '0') {
        // 待批复变更索赔
        this.$router.push({
          name: 'sj-sjxxzhbb-jjwjsj-dpfbgspb',
          params: {
            record: JSON.stringify(record),
          },
        })
      } else if (e.key == '1') {
        // 已发生未列账成本
        this.$router.push({
          name: 'sj-sjxxzhbb-jjwjsj-yfswlzcbb',
          params: {
            record: JSON.stringify(record),
          },
        })
      }
    },
    // 编辑 -->
    edit(id) {
      this.editingKey = id
      let NewData = [...this.dataSource]
      let targetRowData = NewData.find((item) => id === item.id)
      if (targetRowData) {
        targetRowData.editable = true
        this.dataSource = NewData
      }
    },
    //  取消编辑
    cancel(id) {
      let NewData = [...this.dataSource]
      let targetRowData = NewData.find((item) => id === item.id)
      this.editingKey = ''
      if (targetRowData) {
        delete targetRowData.editable
        Object.assign(
          targetRowData,
          this.cacheData.find((item) => id === item.id)
        )
        this.dataSource = NewData
      }
    },
    // 保存
    save(id) {
      let NewData = [...this.dataSource]
      let targetRowData = NewData.find((item) => id === item.id)

      // klygjj: '24',
      // dpfygjj: '25',
      // htlycb: '26',
      // yfswlcb: '27',
      // xlclcb: '28',
      // kllr: '30=24+25-26-27+28',
      let a24 = BigJs(Number(targetRowData['klygjj']))
      let a25 = BigJs(Number(targetRowData['dpfygjj']))
      let a26 = BigJs(Number(targetRowData['htlycb']))
      let a27 = BigJs(Number(targetRowData['yfswlcb']))
      let a28 = BigJs(Number(targetRowData['xlclcb']))
      let testSuccess = (Number(targetRowData['kllr']) == a24.plus(a25).minus(a26).minus(a27).plus(a28))
      if (testSuccess) {
        this.editingKey = ''
        delete targetRowData.editable
        this.SaveEditRowData(targetRowData)
      } else {
        this.$message.error('开累利润计算有误')
      }
    },
    SaveEditRowData(record) {
      if (this.url.saveRowData == '') {
        this.$message.warning('this.url.saveRowData 为空无法保存')
        return;
      }

      // let data = JSON.stringify(record)
      putAction(this.url.saveRowData, { ...record }).then(res => {
        if (res.success) {
          this.CurrentPageEnhanceLoad()
          this.$message.success(res.result)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //  删除
    Delete(record) {
      deleteAction(this.url.delete, { id: record.id }).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.CurrentPageEnhanceLoad()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //  input-number 改变时
    handleChange(value, id, column, type = "int") {
      console.log(value);
      let NewData = [...this.dataSource]
      let targetRowData = NewData.find((item) => id === item.id)
      if (targetRowData) {
        if (type === "int")
          targetRowData[column] = Number.parseInt(value || 0)
        else if (type === "float")
          targetRowData[column] = Number(value || 0)
        this.dataSource = NewData
      }
    },
    //  input 输入框改变时  时间 文本域  普通输入框
    handleChangeInput(value, id, column, type = "text") {
      let NewData = [...this.dataSource]
      let targetRowData = NewData.find((item) => id === item.id)
      if (targetRowData) {
        if (type === "text") {
          // 普通文本
          targetRowData[column] = value
        }
        else if (type === "date") {
          // 日期
          this.yearPickShow = ""
          if (value)
            targetRowData[column] = moment(value).format('YYYY年MM月')
          else
            targetRowData[column] = null
        }
        this.dataSource = NewData
      }
    },
    //  一键提交点击方法
    SubmitDataId(jjwjfblx) {
      putAction(this.url.upDataFlag, { jjwjfblx, submitFlag: 0, ids: this.reportSelectIds }).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
        this.EnhanceLoad()
        this.reportSelectIds = []
      })
    },
    // 明细表1 和 明细表2 的导出
    OnTestExportList(params) {
      getAction(this.url.exportList, params).then((res) => {
        if (res.success && res.result) {
          this.$message.success('正在下载，请稍等！')
          const url = `${window._CONFIG['domianURL']}/sys/common/static${res.result}`
          window.open(url, '_blank')
        } else {
        }
      })
    },
    handlePanelChange(value) {

    },
    // 弹出日历和关闭日历的回调
    handleOpenChange(status) {
      this.yearPickShow = status
    },


  },
}
